package com.xysq.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.rockcent.action.AppAction;
import com.rockcent.action.CallbackListener;
import com.rockcent.action.impl.AppActionImpl;
import com.rockcent.model.CommentModel;
import com.rockcent.model.CommentVModel;
import com.rockcent.model.CustomerBO;
import com.rockcent.model.CustomerCouponBO;
import com.rockcent.model.constant.CustomerCouponState;
import com.rockcent.model.constant.CustomerCouponType;
import com.umeng.analytics.MobclickAgent;
import com.xysq.XYApplication;
import com.xysq.activity.AuthorInformationActivity;
import com.xysq.activity.ImagesActivity;
import com.xysq.adapter.EvaluateAdapterVOnePointOne;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.widget.LoadMoreListView;
import com.xysq.widget.XYBannerHelper;
import com.xysq.widget.XYBannerInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class TipsDetailsFragment extends Fragment implements XYBannerHelper.OnItemClickListener {

    private static final String couponModelId = "couponModelId";
    private int id;
    ImageButton imageButton;
    TextView contentTxt;
    TextView titleTxt;
    TextView priceTxt;
    TextView numberTxt;
    TextView nullDataTxt;
    TextView nameTxt;
    ImageView nextImg;
    com.xysq.widget.CircleImageView headImg;
    ImageView sexImg;
    TextView schoolTxt;
    com.xysq.widget.LoadMoreListView detailsList;

    EvaluateAdapterVOnePointOne evaluateAdapterVOnePointOne;
    ArrayList<CommentVModel> commentVModels;
    private XYBannerHelper goodsBanner;
    private String picUrls;
    private String picUrl[];
    private int picSize;
    int currentPage = 1;

    public AppAction appAction;

    private OnFragmentInteractionListener mListener;

    // TODO: Rename and change types and number of parameters
    public static TipsDetailsFragment newInstance(int mCouponModelId) {
        TipsDetailsFragment fragment = new TipsDetailsFragment();
        Bundle args = new Bundle();
        args.putInt(couponModelId, mCouponModelId);
        fragment.setArguments(args);
        return fragment;
    }

    public TipsDetailsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getInt(couponModelId);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_customer_goods_v_one_point_one, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void loadData() {
        loadCCoupon();
        getComments();
    }

    private void getComments() {
        appAction.listComment(id, currentPage, 20, new CallbackListener<List<CommentModel>>() {
            @Override
            public void onSuccess(List<CommentModel> data) {
                int size = data.size();
                if (currentPage == 1 && size == 0) {
                    nullDataTxt.setVisibility(View.VISIBLE);
                } else {
                    if(currentPage == 1) {
                        commentVModels.clear();
                        for (int i = 0; i < size; i++) {
                            CommentVModel commentVModel = new CommentVModel();
                            if (null != data.get(i).getCommentNickName() && null != data.get(i).getCommentUserName() && null != data.get(i).getCommentUserPhoneNum()) {
                                commentVModel.setName(UseUtil.selectName(data.get(i).getCommentNickName(), data.get(i).getCommentUserName(), data.get(i).getCommentUserPhoneNum()));
                            }
                            commentVModel.setComment(data.get(i).getContent());
                            commentVModel.setHeadUrl(data.get(i).getHeadimgurl());
                            commentVModels.add(commentVModel);
                        }
                        evaluateAdapterVOnePointOne.notifyDataSetChanged();
                    }else {
                        for (int i = 0; i < size; i++) {
                            CommentVModel commentVModel = new CommentVModel();
                            if (null != data.get(i).getCommentNickName() && null != data.get(i).getCommentUserName() && null != data.get(i).getCommentUserPhoneNum()) {
                                commentVModel.setName(UseUtil.selectName(data.get(i).getCommentNickName(), data.get(i).getCommentUserName(), data.get(i).getCommentUserPhoneNum()));
                            }
                            commentVModel.setComment(data.get(i).getContent());
                            commentVModel.setHeadUrl(data.get(i).getHeadimgurl());
                            commentVModels.add(commentVModel);
                        }
                        evaluateAdapterVOnePointOne.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e("++++++++++" + errorCode, message);
                ToastUtil.showShort(getActivity(), "获取评论失败");
            }
        });
    }

    private void loadCCoupon() {
        appAction.viewCustomerCoupon(id, new CallbackListener<CustomerCouponBO>() {
            @Override
            public void onSuccess(CustomerCouponBO data) {
                titleTxt.setText(data.getName());
                priceTxt.setText(UseUtil.handlePrice(data.getPrice()));
                numberTxt.setText("已被打赏" + data.getSaleCount() + "次");
                contentTxt.setText(data.getIntroduce());
                picUrls = data.getPicUrl();
                picUrl = split(picUrls);
                picSize = picUrl.length;
                CustomerCouponState customerCouponState = data.getState();
                Button stateBtn = (Button) getActivity().findViewById(R.id.btn_buy_now);
                if (data.getPrice() == 0) {
                    stateBtn.setEnabled(false);
                } else if (customerCouponState == CustomerCouponState.SALE_OUT) {
                    stateBtn.setText("已下架");
                    stateBtn.setClickable(false);
                    stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                } else if (data.getType() == CustomerCouponType.SKILL) {
                    if (data.getIssueCount() - data.getLockedCount() - data.getSaleCount() <= 0) {
                        stateBtn.setText("已售完");
                        stateBtn.setClickable(false);
                        stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    }
                } else {
                    stateBtn.setEnabled(true);
                }
                loadCustomer(data.getCustomerId());
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.w(errorCode, message);
            }
        });
    }

    private void loadCustomer(final int customerId) {
        appAction.getCustomer("", "", String.valueOf(customerId), new CallbackListener<CustomerBO>() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onSuccess(CustomerBO data) {
                Log.e("++++++", "获取用户信息成功" + " imgUrl" + " " + data.getHeadUrl());
                if (!TextUtils.isEmpty(data.getHeadUrl()) && !data.getHeadUrl().equals("") && !data.getHeadUrl().equals("null")) {
                    String imageUrl = data.getHeadUrl();
                    if (imageUrl.startsWith("http://")) {
                        XYApplication.getImageLoader().displayImage(imageUrl, headImg);
                    } else {
                        XYApplication.getImageLoader().displayImage(PropertiesUtil.getImageServer() + imageUrl, headImg);
                    }
                }
                if (null != data.getSex()) {
                    setSexImg(data.getSex());
                }
                String name = UseUtil.selectName(data.getNickname(), data.getName(), data.getPhone());
                nameTxt.setText(name);
                schoolTxt.setText(data.getSchoolName());
                getHeadPic();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(getActivity(), "获取用户信息失败" + message + customerId);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setSexImg(String sex) {
        if (sex.equals("1")) {
            sexImg.setBackground(getResources().getDrawable(R.drawable.ic_nan));
        } else {
            sexImg.setBackground(getResources().getDrawable(R.drawable.ic_nv));
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initView() {
        commentVModels = new ArrayList<>();
        final View header = View.inflate(getActivity(), R.layout.fragment_customer_goods_v_one_point_one_head, null);//这是头部内容
        final View bottom = View.inflate(getActivity(), R.layout.null_data, null);//这是头部内容
        imageButton = (ImageButton) getView().findViewById(R.id.ibtn_back);
        detailsList = (com.xysq.widget.LoadMoreListView) getView().findViewById(R.id.list_details);
        headImg = (com.xysq.widget.CircleImageView) getView().findViewById(R.id.img_head);
        sexImg = (ImageView) getView().findViewById(R.id.img_sex);
        nextImg = (ImageView) getView().findViewById(R.id.img_next);
        schoolTxt = (TextView) getView().findViewById(R.id.txt_school);
        nameTxt = (TextView) getView().findViewById(R.id.txt_name);

        nullDataTxt = (TextView) bottom.findViewById(R.id.txt_null_data);
        contentTxt = (TextView) header.findViewById(R.id.txt_content_of_tips);
        titleTxt = (TextView) header.findViewById(R.id.txt_title_of_tips);
        priceTxt = (TextView) header.findViewById(R.id.txt_price);
        numberTxt = (TextView) header.findViewById(R.id.txt_number);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        detailsList.addHeaderView(header);
        detailsList.addFooterView(bottom);
        appAction = AppActionImpl.getInstance(getActivity(), PropertiesUtil.getXyapiAddress(), PropertiesUtil.getQkapiAddress());
        evaluateAdapterVOnePointOne = new EvaluateAdapterVOnePointOne(getActivity(), commentVModels);
        detailsList.setAdapter(evaluateAdapterVOnePointOne);
        nextImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), AuthorInformationActivity.class);
                startActivity(intent);
            }
        });
        detailsList.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new LoadDataTask().execute();
            }
        });
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(int index, View v) {
        Intent intent = new Intent(getActivity(), ImagesActivity.class);
        intent.putExtra(ImagesActivity.PARAM_CURRENT_POSITION, index);
        ArrayList picList = new ArrayList<>();
        for (String pic : picUrl) {
            picList.add(pic);
        }
        intent.putStringArrayListExtra(ImagesActivity.PARAM_IMAGE_URLS, picList);
        getActivity().startActivity(intent);
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    private String[] split(String picUrls) {
        if (!TextUtils.isEmpty(picUrls)) {
            String[] picUrl = picUrls.split(";");
            return picUrl;
        } else {
            String[] a = {"picture"};
            return a;
        }
    }

    private void getHeadPic() {
        ArrayList<XYBannerInfo> infos = new ArrayList<XYBannerInfo>() {{
            for (int i = 0; i < picSize; i++) {
                if (picUrl[i].startsWith("http://")) {
                    add(new XYBannerInfo("", picUrl[i]));
                } else {
                    add(new XYBannerInfo("", PropertiesUtil.getImageServer() + picUrl[i]));
                }
            }
        }};
        goodsBanner = new XYBannerHelper(getActivity());
        goodsBanner.setBannerInfo(infos);
        goodsBanner.startAutoRoll();
        goodsBanner.setOnItemClickCallback(this);
    }

    private String timeChangeFormat(Long data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String time = format.format(data);
        return time;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (goodsBanner != null) {
            goodsBanner.destroyHelper();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        currentPage = 1;
        loadData();
        MobclickAgent.onPageStart("技能详情页");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("技能详情页");
        if (goodsBanner != null) {
            goodsBanner.stopAutoRoll();
        }
    }

    private class LoadDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            if (isCancelled()) {
                return null;
            }
            try {
                Thread.sleep(1000);
                currentPage++;
                getComments();
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
//            evaluateAdapterVOnePointOne.notifyDataSetChanged();
            detailsList.onLoadMoreComplete();
            super.onPostExecute(result);
        }

        @Override
        protected void onCancelled() {
            detailsList.onLoadMoreComplete();
        }
    }
}
